﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Cofe.Core;
using Cofe.Web.Models;
using Cofe.Web.Utils;
using WebMatrix.WebData;

namespace Cofe.Web.Controllers.Admin
{
    [Authorize(Roles = "Admin")] 
    public class PermissionController : Controller
    {

        //
        // GET: /Permission/
        public ViewResult Index(string editName = null)
        {
            ViewBag.EditName = editName;
            ViewBag.PossibleRoles = WebUserRoleUtils.PossibleRoles;

            string[] userNames;
            using (UsersContext db = new UsersContext())
            {
                userNames = db.UserProfiles.Select(up => up.UserName).ToArray();
            }

            IEnumerable<UserInfoViewModel> vms = from u in userNames
                                                 select UserInfoViewModel.FromUser(u, "Forms");

            return View(vms);
        }

        // POST: /Permission/Save
        [HttpPost, ActionName("Index")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Save(UserInfoViewModel userVm)
        {
            if (userVm.Role == WebUserRole.Admin)
                throw new NotSupportedException();

            //return PartialView(UserInfoViewModel.FromUser(userName, "Forms", roleList));
            UserInfoViewModel orgVm = UserInfoViewModel.FromUser(userVm.AccountName, userVm.AuthenticateType);
            
            UserFE.RevokeRole(orgVm.AccountName);
            WSUserManager.SetRole(orgVm.AccountName, userVm.Role);

            //if (userVm.Role != WebUserRole.Other)
            //    UserFE.GrantRole(userVm.AccountName, userVm.AuthenticateType, userVm.RoleString);
            
            await CofeServices.SaveAsync();
            return RedirectToAction("Index");
        }

    }
}
